<?php

class TableEditView {

    private static $me = NULL;

    public static function getInstance() {
        if (!self::$me instanceof TableEditView) {
            self::$me = new TableEditView();
        }

        return self::$me;
    }

    
    public function getTableEditTemplate($tableID = 0) {
        $template = '';
        if ($tableID == 0) {
            $template = $this->_getTableEditNewTemplate();
        } else {
            $template = $this->_getTableEditPopulatedTemplate($tableID);
        }
        return $template;
    }

    private function _getTableEditNewTemplate() {
        $xtpl = new XTemplate(Utility::getFileContent(DIR_TEMPLATES . DS . 'table.edit.main.tpl.html'));
        //$xtpl->assign('field_rows', $this->getEmptyFieldRowTemplate());
        $xtpl->assign('field_rows', '');
        $xtpl->parse('main');
        return $xtpl->out('main');
    }

    private function _getTableEditPopulatedTemplate($tableID) {
        $xtpl = new XTemplate(Utility::getFileContent(DIR_TEMPLATES . DS . 'table.edit.main.tpl.html'));
        $xtpl->assign('table', new Table($tableID));
        $fieldIDs = TableManager::getInstance()->getTableFields($tableID);
        $fields = '';
        foreach ($fieldIDs as $fieldID) {
            $fields .= $this->getPopulatedFieldRowTemplate($fieldID);
        }
        $xtpl->assign('field_rows', $fields);
        $xtpl->parse('main');
        return $xtpl->out('main');
    }
    public function getEmptyFieldRowTemplate()
    {
        $xtpl = new XTemplate(Utility::getFileContent(DIR_TEMPLATES . DS . 'table.edit.field.tpl.html'));
        $xtpl->parse('main');
        return $xtpl->out('main');
        
    }
    private function getPopulatedFieldRowTemplate($fieldID){
        $xtpl = new XTemplate(Utility::getFileContent(DIR_TEMPLATES . DS . 'table.edit.field.tpl.html'));
        $field = new Field($fieldID);
        
        $xtpl->assign('field', $field);
        $checked = '';
        if($field->getIsPrimary()){
            $xtpl->assign('primary_checked', 'checked="checked"');
        }
        else{
            $xtpl->assign('primary_checked', '');
        }
        $xtpl->assign('rowColor', Utility::getRowColor());
        $xtpl->parse('main');
        return $xtpl->out('main');
    }

}
